package com.ias.agdis_r.db;

import java.lang.reflect.Method;
import java.util.Locale;

import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.JavaBeanManager;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * 
 * @author qibo.yu
 * @version 2015年8月18日 上午8:54:45
 **/
public class MyBeanTempDBHelper<T> extends SQLiteOpenHelper {

	private static final String DB_NAME = "temp_data.db3";
	private static final int DB_VERSION = 2;

	private Class<T> clazz;
	private String tabelName;

	public MyBeanTempDBHelper(Context context, Class<T> clazz) {
		super(context, DB_NAME, null, DB_VERSION);
		this.clazz = clazz;
		this.tabelName = clazz.getName().replaceAll("\\.", "_");
	}

	public void creatTable() {
		SQLiteDatabase db = getWritableDatabase();
		db.execSQL("CREATE TABLE IF NOT EXISTS " + BoxDBHelper.TABLE_FLIGHT
				+ "(fke VARCHAR(255),msg VARCHAR(255),type VARCHAR(255),time VARCHAR(255),enb VARCHAR(255),ischeck VARCHAR(255),_id INTEGER PRIMARY KEY AUTOINCREMENT)");
		db.execSQL("CREATE TABLE IF NOT EXISTS " + BoxDBHelper.TABLE_TASK
				+ "(tnb VARCHAR(255),msg VARCHAR(255),type VARCHAR(255),time VARCHAR(255),enb VARCHAR(255),ischeck VARCHAR(255),_id INTEGER PRIMARY KEY AUTOINCREMENT,fke VARCHAR(255),fln VARCHAR(255))");
		db.execSQL("CREATE TABLE IF NOT EXISTS " + BoxDBHelper.TABLE_TASKPROCESS
				+ "(tnb VARCHAR(255),title VARCHAR(255),msg VARCHAR(255),time VARCHAR(255),enb VARCHAR(255),_id INTEGER PRIMARY KEY AUTOINCREMENT)");
		db.execSQL("CREATE TABLE IF NOT EXISTS " + BoxDBHelper.TABLE_LUGGAGEBARCODE
				+ "(fkey VARCHAR(255),flop VARCHAR(255),flno VARCHAR(255),adid VARCHAR(255),tnb VARCHAR(255),enb VARCHAR(255),barcode VARCHAR(255),scanTime VARCHAR(255),state VARCHAR(255),_id INTEGER PRIMARY KEY AUTOINCREMENT, UNIQUE(fkey, tnb, enb, barcode))");
		db.execSQL("CREATE TABLE IF NOT EXISTS " + BoxDBHelper.TABLE_TASKCHOOSEMEMBER
				+ "(tnb VARCHAR(255),enb VARCHAR(255),members VARCHAR(255),time VARCHAR(255),_id INTEGER PRIMARY KEY AUTOINCREMENT, UNIQUE(tnb, enb))");
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		StringBuilder sqlBuilder = new StringBuilder("CREATE TABLE IF NOT EXISTS ").append(tabelName).append("(");
		for (Method method : clazz.getMethods()) {
			String name = method.getName();
			if (name.startsWith("get") && !name.equals("getClass")) {
				String colName = getColName(name);
				sqlBuilder.append(colName).append(" VARCHAR(255) ");
				if (colName.equals("_id")) {
					sqlBuilder.append("PRIMARY KEY ");
				}
				sqlBuilder.append(",");
			}
		}
		if (sqlBuilder.indexOf("_id") == -1) {
			sqlBuilder.append("_id INTEGER PRIMARY KEY AUTOINCREMENT,");
		}
		sqlBuilder.append("user_name VARCHAR(255),");
		sqlBuilder.replace(sqlBuilder.length() - 1, sqlBuilder.length(), ");");
		db.execSQL(sqlBuilder.toString());
		Log.i("C_db", "db table create:" + sqlBuilder.toString());
	}

	@Override
	public SQLiteDatabase getWritableDatabase() {
		// TODO Auto-generated method stub
		SQLiteDatabase db = super.getWritableDatabase();
		String sql = "select count(*) from sqlite_master where type = 'table' and name = '" + getTableName() + "'";
		Cursor cursor = db.rawQuery(sql, null);
		cursor.moveToFirst();
		int count = cursor.getInt(0);
		cursor.close();
		Log.d("C_db", getTableName() + " exist sql:" + sql);
		Log.d("C_db", getTableName() + " exist:" + count);
		if (count == 0) {
			if (!db.isReadOnly()) {
				onCreate(db);
			}
		}
		return db;
	}

	// @Override
	// public void onOpen(SQLiteDatabase db) {
	// String sql = "select count(*) from sqlite_master where type = 'table' and
	// name = '" + getTableName() + "'";
	// if (db.rawQuery(sql, null).getCount() == 0) {
	// if (!db.isReadOnly()) {
	// onCreate(db);
	// }
	// }
	// }

	public String getColName(String methodName) {
		String colName = methodName.substring(3).toLowerCase(Locale.US);
		if (colName.equals("id")) {
			colName = "_id";
		}
		return colName;
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if (oldVersion == 1 && newVersion == 2) {
			String sql = "DROP TABLE 'com_ias_agdis_r_bean_message_MessageTemplate'";
			db.execSQL(sql);
			onCreate(db);
		}
	}

	public String getTableName() {
		return this.tabelName;
	}

	public void insert(SQLiteDatabase db, T col) {
		ContentValues contentValues = new ContentValues();
		for (Method method : col.getClass().getMethods()) {
			String name = method.getName();
			if (name.startsWith("get") && !name.equals("getClass")) {
				String colName = getColName(name);
				try {
					contentValues.put(colName, (String) method.invoke(col));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		contentValues.put("user_name", JavaBeanManager.getInstance().getUserinfo().getEnb());
		db.insert(getTableName(), null, contentValues);
	}

	public void insert(T col) {
		SQLiteDatabase db = getWritableDatabase();
		insert(db, col);
		db.close();
		db = null;
	}

	public static boolean deleteDB() {
		Context context = DataBaseManager.getInstance().getContext();
		if (context != null) {
			// boolean isok = context.deleteDatabase(DB_NAME);
			// Log.d("C_db", "db delete result:" + isok);
		}
		Log.w("C_sys", "DataBaseManager.getInstance().getContext() val is null");
		return true;
	}

}
